{% extends 'assets/base.html' %}
{% load static %}

{% block title %}预测性维护{% endblock %}

{% block extra_css %}
<style>
.prediction-card {
    border-left: 4px solid #28a745;
    transition: all 0.3s ease;
}
.prediction-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.prediction-card.urgent {
    border-left-color: #dc3545;
}
.prediction-card.warning {
    border-left-color: #ffc107;
}
.prediction-card.info {
    border-left-color: #17a2b8;
}
.days-until {
    font-size: 1.2em;
    font-weight: bold;
}
.confidence-bar {
    height: 8px;
    border-radius: 4px;
    background: #e9ecef;
    overflow: hidden;
}
.confidence-fill {
    height: 100%;
    background: linear-gradient(90deg, #dc3545 0%, #ffc107 50%, #28a745 100%);
    transition: width 0.3s ease;
}
.filter-card {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-tools"></i> 预测性维护</h2>
        <div class="btn-group">
            <a href="{% url 'assets:ai_dashboard' %}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> 返回仪表板
            </a>
            <button type="button" class="btn btn-info" onclick="refreshPredictions()">
                <i class="fas fa-sync-alt"></i> 刷新预测
            </button>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-card">
        <form method="get" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">资产类别</label>
                <select name="category" class="form-select">
                    <option value="">全部类别</option>
                    {% for category in categories %}
                    <option value="{{ category.id }}" {% if current_filters.category == category.id|stringformat:"s" %}selected{% endif %}>
                        {{ category.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">所属部门</label>
                <select name="department" class="form-select">
                    <option value="">全部部门</option>
                    {% for department in departments %}
                    <option value="{{ department.id }}" {% if current_filters.department == department.id|stringformat:"s" %}selected{% endif %}>
                        {{ department.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">预测天数</label>
                <select name="days_ahead" class="form-select">
                    <option value="30" {% if current_filters.days_ahead == "30" %}selected{% endif %}>30天</option>
                    <option value="60" {% if current_filters.days_ahead == "60" %}selected{% endif %}>60天</option>
                    <option value="90" {% if current_filters.days_ahead == "90" %}selected{% endif %}>90天</option>
                    <option value="180" {% if current_filters.days_ahead == "180" %}selected{% endif %}>180天</option>
                    <option value="365" {% if current_filters.days_ahead == "365" %}selected{% endif %}>365天</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <div class="d-grid">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-search"></i> 筛选
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 预测结果 -->
    <div class="row">
        {% if page_obj %}
            {% for item in page_obj %}
            {% with asset=item.asset prediction=item.prediction %}
            <div class="col-md-6 mb-3">
                <div class="card prediction-card {% if prediction.days_until <= 7 %}urgent{% elif prediction.days_until <= 30 %}warning{% else %}info{% endif %}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title mb-0">
                                <a href="{% url 'assets:asset_detail' asset.pk %}" class="text-decoration-none">
                                    {{ asset.name }}
                                </a>
                            </h5>
                            <a href="{% url 'assets:ai_asset_prediction_detail' asset.pk %}" class="btn btn-sm btn-outline-info">
                                <i class="fas fa-info-circle"></i> 详情
                            </a>
                        </div>
                        
                        <p class="text-muted mb-2">{{ asset.asset_number }} - {{ asset.category.name }}</p>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <small class="text-muted">预测维护日期:</small><br>
                                <strong>{{ prediction.predicted_date|date:"Y-m-d" }}</strong>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">距离天数:</small><br>
                                <span class="days-until {% if prediction.days_until <= 7 %}text-danger{% elif prediction.days_until <= 30 %}text-warning{% else %}text-info{% endif %}">
                                    {{ prediction.days_until }} 天
                                </span>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <small class="text-muted">预测置信度:</small>
                            <div class="confidence-bar mt-1">
                                <div class="confidence-fill" style="width: {{ prediction.confidence|floatformat:0 }}%"></div>
                            </div>
                            <small class="text-muted">{{ prediction.confidence|floatformat:1 }}%</small>
                        </div>
                        
                        <div class="mb-2">
                            <small class="text-muted">预测模型:</small><br>
                            <span class="badge bg-secondary">{{ prediction.model_type }}</span>
                        </div>
                        
                        <div class="mb-2">
                            <small class="text-muted">维护建议:</small><br>
                            <span class="text-info">{{ prediction.recommendation }}</span>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                {% if asset.department %}
                                <span class="badge bg-outline-secondary">{{ asset.department.name }}</span>
                                {% endif %}
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-success" onclick="scheduleMaintenance({{ asset.pk }})" title="安排维护">
                                    <i class="fas fa-calendar-plus"></i>
                                </button>
                                <button class="btn btn-info" onclick="viewHistory({{ asset.pk }})" title="查看历史">
                                    <i class="fas fa-history"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endwith %}
            {% endfor %}
        {% else %}
            <div class="col-12">
                <div class="text-center py-5">
                    <i class="fas fa-tools fa-4x text-muted mb-3"></i>
                    <h4 class="text-muted">暂无预测数据</h4>
                    <p class="text-muted">系统正在分析资产数据，请稍后查看预测结果</p>
                    <button type="button" class="btn btn-info" onclick="refreshPredictions()">
                        <i class="fas fa-sync-alt"></i> 刷新预测
                    </button>
                </div>
            </div>
        {% endif %}
    </div>

    <!-- 分页 -->
    {% if page_obj.has_other_pages %}
    <nav aria-label="预测性维护分页">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    上一页
                </a>
            </li>
            {% endif %}
            
            {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
            <li class="page-item active">
                <span class="page-link">{{ num }}</span>
            </li>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
            <li class="page-item">
                <a class="page-link" href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    {{ num }}
                </a>
            </li>
            {% endif %}
            {% endfor %}
            
            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    下一页
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
</div>

<!-- 安排维护模态框 -->
<div class="modal fade" id="maintenanceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">安排维护</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="maintenanceForm">
                    <div class="mb-3">
                        <label class="form-label">维护类型</label>
                        <select name="maintenance_type" class="form-select" required>
                            <option value="">请选择维护类型</option>
                            <option value="preventive">预防性维护</option>
                            <option value="corrective">纠正性维护</option>
                            <option value="emergency">紧急维护</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">计划日期</label>
                        <input type="date" name="planned_date" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">维护描述</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="请输入维护描述..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">预估成本</label>
                        <input type="number" name="estimated_cost" class="form-control" step="0.01" min="0">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="submitMaintenance()">安排维护</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentAssetId = null;

// 刷新预测
function refreshPredictions() {
    showLoading('正在刷新预测数据...');
    setTimeout(() => {
        hideLoading();
        location.reload();
    }, 2000);
}

// 安排维护
function scheduleMaintenance(assetId) {
    currentAssetId = assetId;
    
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.querySelector('input[name="planned_date"]').value = today;
    
    const modal = new bootstrap.Modal(document.getElementById('maintenanceModal'));
    modal.show();
}

function submitMaintenance() {
    const form = document.getElementById('maintenanceForm');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    data.asset_id = currentAssetId;
    
    showLoading('正在创建维护计划...');
    
    // 这里应该调用维护管理的API
    fetch('{% url "assets:maintenance_create" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        hideLoading();
        if (response.ok) {
            showAlert('success', '维护计划已创建');
            bootstrap.Modal.getInstance(document.getElementById('maintenanceModal')).hide();
            form.reset();
        } else {
            showAlert('error', '创建维护计划失败');
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '创建维护计划失败: ' + error.message);
    });
}

// 查看历史
function viewHistory(assetId) {
    window.open(`/assets/assets/${assetId}/`, '_blank');
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showLoading(message) {
    const loading = document.createElement('div');
    loading.id = 'loading-overlay';
    loading.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center';
    loading.style.backgroundColor = 'rgba(0,0,0,0.5)';
    loading.style.zIndex = '9999';
    loading.innerHTML = `
        <div class="bg-white p-4 rounded text-center">
            <div class="spinner-border text-info mb-2"></div>
            <div>${message}</div>
        </div>
    `;
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('loading-overlay');
    if (loading) {
        loading.remove();
    }
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}
</script>
{% endblock %}